#include "string.h"
#include "stdio.h"
#include "stdint.h"
#include "cmsis_os2.h"                  // ::CMSIS:RTOS2
#include "esp32Serial.h"

//#include "stm32f7xx_hal_gpio.h"


extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart6;
extern DMA_HandleTypeDef hdma_usart6_rx;
extern DMA_HandleTypeDef hdma_usart6_tx;


uint8_t serial1TxBuffer[200];
uint8_t serial1RxBuffer[200];

uint8_t serial6TxBuffer[200];
uint8_t serial6RxBuffer[200];

xySerial xySerial6 = 
{
	.txBuf.memPtr 			= serial6TxBuffer,
	.txBuf.memSize 			= 200,
	.txBuf.frameEnable 	= 0,
	.rxBuf.memPtr 			= serial6RxBuffer,
	.rxBuf.memSize 			= 200,
	.rxBuf.frameEnable 	= 0,
	.stat.sending = 0,
	.uart 				= &huart6,
};


xySerial xySerial1 = 
{
	.txBuf.memPtr = serial1TxBuffer,
	.txBuf.memSize = 200,
	.txBuf.frameEnable = 0,
	.rxBuf.memPtr = serial1RxBuffer,
	.rxBuf.memSize = 200,
	.rxBuf.frameEnable = 0,
	.stat.sending = 0,
	.uart = &huart1,
};



typedef const struct  {
  const char *str;
} STRING_LIST_t;




enum esp32AtRepoIndex 
{
	esp32AtRepo_Data=0,

};


int32_t xySerialSendBuf(xySerial* const serial,uint8_t* pBuf,uint32_t len);
int32_t xySerialSenfChar(xySerial* const serial,uint8_t byte);
int32_t xySerialGetChar(xySerial* const serial,uint8_t* byte);
int32_t xySerialClearFifo(xySerial* const serial,uint8_t fifoType);




/*
*Uart6 init 
*/
int32_t uart6Init(void)
{
	softRingBufInit(&xySerial6.rxBuf);
	softRingBufInit(&xySerial6.txBuf);
	
	huart6.Instance = USART6;
  huart6.Init.BaudRate = 115200;
  huart6.Init.WordLength = UART_WORDLENGTH_8B;
  huart6.Init.StopBits = UART_STOPBITS_1;
  huart6.Init.Parity = UART_PARITY_NONE;
  huart6.Init.Mode = UART_MODE_TX_RX;
  huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart6.Init.OverSampling = UART_OVERSAMPLING_16;
  huart6.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart6.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart6) != HAL_OK)
  {
   while(1);
  }
	__HAL_UART_ENABLE_IT(xySerial6.uart,UART_IT_RXNE);
	HAL_NVIC_SetPriority(USART6_IRQn, 0, 1);
	HAL_NVIC_EnableIRQ(USART6_IRQn);
		
	return 0;
}

/*
*uart6 deinit
*/
int32_t uart6DeInit(void)
{

	
	return 0;
}


/*
*uart6 set baudrate
*/
int32_t uart6setBaud(xySerial* const serial,uint32_t baudRate)
{

	return 0;
}

/*
*Uart1 init
*/
int32_t uart1Init(void)
{
	softRingBufInit(&xySerial1.rxBuf);
	softRingBufInit(&xySerial1.txBuf);
	
	huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
   while(1);
  }
	__HAL_UART_ENABLE_IT(xySerial1.uart,UART_IT_RXNE);
	HAL_NVIC_SetPriority(USART1_IRQn, 0, 1);
	HAL_NVIC_EnableIRQ(USART1_IRQn);
	return 0;
}


/*
*uart1 deinit
*/
int32_t uart1DeInit(void)
{

	return 0;
}

/*
*uart1 set baudrate
*/
int32_t uart1setBaud(xySerial* const serial,uint32_t baudRate)
{

	return 0;
}




/*
*uart irq handler
*/
void uartIrqHandler(xySerial* const serial)
{
	uint8_t ch;
	//读取isr和cr
	uint32_t isrflags = READ_REG(serial->uart->Instance->ISR);
	uint32_t cr1its = READ_REG(serial->uart->Instance->CR1);
	uint32_t cr3its = READ_REG(serial->uart->Instance->CR3);

    /* 处理接收中断  */
    if ((isrflags & USART_ISR_RXNE) != RESET)
    {
        /* 从串口接收数据寄存器读取数据存放到接收FIFO */
				serial->rxBuf.putChar(&serial->rxBuf,READ_REG(serial->uart->Instance->RDR));

        /* 回调函数,通知应用程序收到新数据,一般是发送1个消息或者设置一个标记 */
				if(serial->dataReadyCallback) serial->dataReadyCallback(0);
    }

    /* 处理发送缓冲区空中断 */
    if (((isrflags & USART_ISR_TXE) != RESET) && (cr1its & USART_CR1_TXEIE) != RESET)
    {
        if(serial->txBuf.amount(&serial->txBuf) == 0)
				{
            /* 发送缓冲区的数据已取完时， 禁止发送缓冲区空中断 （注意：此时最后1个数据还未真正发送完毕）*/
            //USART_ITConfig(_pUart->uart, USART_IT_TXE, DISABLE);
            CLEAR_BIT(serial->uart->Instance->CR1, USART_CR1_TXEIE);

            /* 使能数据发送完毕中断 */
            SET_BIT(serial->uart->Instance->CR1, USART_CR1_TCIE);
        }
        else
        {
            serial->stat.sending = true;

            /* 从发送FIFO取1个字节写入串口发送数据寄存器 */
						serial->txBuf.getChar(&serial->txBuf,&ch);
            serial->uart->Instance->TDR = ch;
        }
    }
    /* 数据bit位全部发送完毕的中断 */
    if (((isrflags & USART_ISR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET))
    {
        //if (_pUart->usTxRead == _pUart->usTxWrite)
        if (serial->txBuf.amount(&serial->txBuf) == 0)
        {
            /* 如果发送FIFO的数据全部发送完毕，禁止数据发送完毕中断 */
            //USART_ITConfig(_pUart->uart, USART_IT_TC, DISABLE);
            CLEAR_BIT(serial->uart->Instance->CR1, USART_CR1_TCIE);

            /* 回调函数, 一般用来处理RS485通信，将RS485芯片设置为接收模式，避免抢占总线 */
						if( serial->sendCompleteCallback ) serial->sendCompleteCallback();
            serial->stat.sending = false;
        }
        else
        {
            serial->txBuf.getChar(&serial->txBuf,&ch);
            serial->uart->Instance->TDR = ch;
        }
    }

    /* 清除中断标志 */
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_PEF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_FEF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_NEF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_OREF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_IDLEF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_TCF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_LBDF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_CTSF);
    SET_BIT(serial->uart->Instance->ICR, UART_CLEAR_CMF);

}




/*
*serial 初始化
*/
int32_t xySerialInit(xySerial* const serial)
{
	if(serial == &xySerial1)
	{
		serial->uart = &huart1;
		serial->uartInit = uart1Init;
		serial->uartDeInit = uart1DeInit;
		serial->uartSetBaud = uart1setBaud;
		serial->uartInit();
	}else if(serial == &xySerial6){
		serial->uart = &huart6;
		serial->uartInit = uart6Init;
		serial->uartDeInit = uart6DeInit;
		serial->uartSetBaud = uart6setBaud;
		serial->uartInit();
	}
	
	serial->sendBuf = xySerialSendBuf ;
	serial->senfChar = xySerialSenfChar ;
	serial->getChar = xySerialGetChar ;
	serial->clearBuffer = xySerialClearFifo ;
	
	return 0;
}

/*
*发送buf
*/
int32_t xySerialSendBuf(xySerial* const serial,uint8_t* pBuf,uint32_t len)
{
	
	if(serial->txBuf.putData(&serial->txBuf,pBuf,len) == soft_OK)
	{
		 SET_BIT(serial->uart->Instance->CR1, USART_CR1_TXEIE); /* 使能发送中断（缓冲区空） */
	}
	return 0;
}

/*
*发送字符
*/
int32_t xySerialSenfChar(xySerial* const serial,uint8_t byte)
{
	return xySerialSendBuf(serial,&byte,1);
}

/*
*读取一个字符
*/
int32_t xySerialGetChar(xySerial* const serial,uint8_t* byte)
{
	return serial->rxBuf.getChar(&serial->rxBuf,byte);
}


/*
*清空FIFO
*/
int32_t xySerialClearFifo(xySerial* const serial,uint8_t fifoType)
{
	if(fifoType) return serial->rxBuf.clear(&serial->rxBuf);
		else return serial->txBuf.clear(&serial->txBuf);
	
}





/*
* uart6 irq handler
*/
void USART6_IRQHandler(void)
{
  uartIrqHandler(&xySerial6);
}

/*
* uart1 irq handler
*/
void USART1_IRQHandler(void)
{
  uartIrqHandler(&xySerial1);
}


void DMA2_Stream1_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream1_IRQn 0 */

  /* USER CODE END DMA2_Stream1_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart6_rx);
  /* USER CODE BEGIN DMA2_Stream1_IRQn 1 */

  /* USER CODE END DMA2_Stream1_IRQn 1 */
}

/**
  * @brief This function handles DMA2 stream6 global interrupt.
  */
void DMA2_Stream7_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream6_IRQn 0 */

  /* USER CODE END DMA2_Stream6_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart6_tx);
  /* USER CODE BEGIN DMA2_Stream6_IRQn 1 */

  /* USER CODE END DMA2_Stream6_IRQn 1 */
}



